package com.practice.dsa.interviewclassic6;

import java.util.HashMap;
import java.util.Map;

/**
 * 描述
 *
 * @author yaokun.zhang
 * @version 1.0
 * @date 2022-11-08 16:58:01
 */
public class CheckPermutation {

    public boolean CheckPermutation(String s1, String s2) {
        int length1 = s1.length();
        int length2 = s2.length();
        //长度判断
        if(length1 != length2){
            return false;
        }
        //记录历史值
        Map<Character, Integer> map1 = new HashMap<>();
        Map<Character, Integer> map2 = new HashMap<>();
        for(int i = 0; i < length1; i++){
            putChar(map1, s1.charAt(i));
            putChar(map2, s2.charAt(i));
        }
        //遍历出现次数 < 2 false
        for(char ch : map1.keySet()){
            int c1 = map1.getOrDefault(ch, 0);
            int c2 = map2.getOrDefault(ch, 0);
            if(c1 != c2){
                return false;
            }
        }

        return true;
    }

    //存放字符
    public void putChar(Map<Character, Integer> map, char c){
        int count = map.getOrDefault(c, 0);
        map.put(c, ++count);
    }

    public boolean CheckPermutation2(String s1, String s2) {
        int length1 = s1.length();
        int length2 = s2.length();
        //长度判断
        if(length1 != length2){
            return false;
        }
        //遍历S1 记录出现次数
        int[] t = new int[128];
        for(int i = 0; i < length1; i++){
            t[s1.charAt(i)] ++;
        }

        for(int i = 0; i < length1; i++){
            t[s2.charAt(i)] --;
            if(t[s2.charAt(i)] < 0){
                return false;
            }
        }

        return true;
    }

}
